import 'dart:convert';
import 'dart:developer';

import '../../index.dart';

typedef FilterCallback = void Function(List<FilterSelectData> selectList);

enum FilterWidgetStyle { defaultStyle /* 0 */, roundStyle }

class FilterButton extends StatefulWidget {
  FilterCallback onSelect;
  FilterCallback? onInit;
  String? initConfigJson;
  FilterItemData? initConfig;

  FilterButton(
      {Key? key,
      this.initConfigJson,
      this.initConfig,
      required this.onSelect,
      this.onInit})
      : super(key: key);

  @override
  State<StatefulWidget> createState() => _FilterWidgetState();
}

class _FilterWidgetState extends State<FilterButton> {
  final GlobalKey globalKey = GlobalKey();
  FilterItemData? itemData;
  int clickTimeMillis = 0;

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    // 解析初始化配置

    if (widget.initConfig == null) {
      // if (widget.initConfigJson != null) {
      //   Debug.info("${widget.initConfigJson}");
      //   var config = jsonDecode(widget.initConfigJson!);
      //   itemData = FilterItemData.fromJson(config);
      // }
      itemData = FilterUtils.jsonToFilterData(widget.initConfigJson);
    } else {
      itemData = widget.initConfig!;
    }
    if (widget.onInit != null) {
      //初始化完成后 调用一次 返回最新的选中内容
      _handleSelectData(isInit: true);
    }
  }

  @override
  Widget build(BuildContext context) {
    return Column(
      key: globalKey,
      children: [
        const Divider(
          height: 1,
        ),
        SizedBox(height: 50, child: _buildBody()),
        const Divider(
          height: 1,
        )
      ],
    );
  }

  Widget _buildBody() {
    if (itemData != null) {
      return TextButton(
          onPressed: () {
            if (itemData!.children != null) {
              // 2次点击间隔0.5s 避免动画出现bug
              int currentTimeMillis = DateTime.now().millisecondsSinceEpoch;
              if (currentTimeMillis - clickTimeMillis < 500) {
                return;
              } else {
                clickTimeMillis = currentTimeMillis;
              }
              //设置偏移值
              Offset offsetLT = const Offset(50, 0);

              filterPopup(
                  context,
                  FilterRightPage(
                      itemData: itemData!,
                      onSelect: (FilterItemData filterItemData) {
                        //更新itemData
                        itemData = filterItemData;
                        _handleSelectData();
                      },
                      onDismiss: () {},
                      offsetLT: offsetLT),
                  offsetLT: Offset.zero);
            }
          },
          child: Text("筛选",
              style: Theme.of(context)
                  .textTheme
                  .bodyMedium
                  ?.copyWith(color: Theme.of(context).primaryColor)));
    } else {
      return Container();
    }
  }

  void _handleSelectData({bool isInit = false}) {
    if (itemData != null) {
      List<FilterSelectData> selectList = [];

      for (FilterItemData filterItemData in itemData!.children!) {
        //如果被修改的是一个箭头 只修改单选数据
        for (FilterItemData childItemData in filterItemData.children!) {
          if (childItemData.select == 1) {
            //选中第一项
            addValue(selectList, filterItemData.code, childItemData.value);
          } else if (childItemData.select == 2) {
            //选中第二项
            addValue(selectList, filterItemData.code,
                "【asc】-${childItemData.value}");
          }
        }
      }

      if (isInit) {
        if (widget.onInit != null) {
          widget.onInit!(selectList);
        }
      } else {
        widget.onSelect(selectList);
      }
    }
  }

  void addValue(
      List<FilterSelectData> selectList, String? code, String? value) {
    if (code != null && value != null) {
      for (FilterSelectData selectData in selectList) {
        if (code == selectData.code) {
          if (!selectData.values.contains(value)) {
            selectData.values.add(value);
          }
          return;
        }
      }
      //添加value
      selectList.add(FilterSelectData(code, [value]));
    }
  }
}
